<?php


namespace common\utils;

use support\Response;

/**
 * Class Json
 * @package common\utils
 * @author ycr <Email: yuncran@126.com>
 */
class Json
{

    public function make(int $status, string $msg, ?array $data = null, ?array $replace = []): Response
    {
        $res = compact('status', 'msg');

        if (!is_null($data))
            $res['data'] = $data;
            $res['time'] = time();
        // TODO 多语言用
//        if (is_numeric($res['msg']))
//            $res['msg'] = getLang($res['msg'], $replace);

        return new Response(200, ['Content-Type' => 'application/json'], json_encode($res, JSON_UNESCAPED_UNICODE));
    }

    public function success($msg = 'success', ?array $data = null, ?array $replace = []): Response
    {
        if (is_array($msg)) {
            $data = $msg;
            $msg = 'success';
        }

        return $this->make(200, $msg, $data, $replace);
    }

    public function fail($msg = 'fail', ?array $data = null, ?array $replace = []): Response
    {
        if (is_array($msg)) {
            $data = $msg;
            $msg = 'fail';
        }

        return $this->make(400, $msg, $data, $replace);
    }

    public function status($status, $msg, $result = [])
    {
        $status = strtoupper($status);
        if (is_array($msg)) {
            $result = $msg;
            $msg = 'success';
        }
        return app('json')->success($msg, compact('status', 'result'));
    }
}